#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../fn85.h"

int
main(int argc, char *argv[])
{
	int a = 0;
	int str_indx = 1;
	size_t len;
	size_t chars = 0;
	unsigned char *binary = NULL;

	if (argc == 3) {
		if (strcmp(argv[1], "-a"))
			goto usage;

		a = 1;
		str_indx = 2;
	} else if (argc != 2) {
		goto usage;
	}

	if ((len = strlen(argv[str_indx])) % 5) {
		printf("Fn85 strings are multiples of 5 in length.\n");
		goto usage;
	}

	if (!len)
		return 0;

	if (!(binary = malloc(len/5 * 4))) {
		printf("Failed to allocate byte buffer");
		return -1;
	}

	switch (fn85_decode(binary, argv[str_indx], len/5, &chars)) {
	case FN85_OKAY:
		break;
	case FN85_INVALID:
		printf("Something wasn't a digit at index %zu.\n", chars);
		goto usage;
	case FN85_TOO_HIGH:
		printf("Number became larger than possible at index %zu.\n",
		       chars);
		goto usage;

	}

	if (!a) {
		for (size_t i = 0; i < len/5 * 4; ++i)
			printf("%02x", binary[i]);

		printf("\n");
		return 0;
	}

	printf("{ ");
	printf("0x%02x", binary[0]);

	for (size_t i = 1; i < len/5 * 4; ++i)
		printf(", 0x%02x", binary[i]);

	printf(" }\n");
	return 0;

usage:
	free(binary);
	printf("Usage\n\tfn85_decode [-a] Fn85_String\n"
	       "This outputs a hex version of the string.\n"
	       "The optional -a flag outputs data in an array format.\n");
	return 0;
}
